#include "stu.h"

ofstream& operator << (ofstream&out,const stu&p)
{
    out<<p.id<<"\t"<<p.name;
    return out;
}

ifstream& operator >> (ifstream&in,stu&p)
{
    in>>p.id>>p.name;
    return in;
}


admin::admin()
{
    system("clear");
    cout<<"请选择需要的操作："<<endl;
    cout<<"1：注册"<<endl;
    cout<<"2：注销"<<endl;
    cout<<"3：查询"<<endl;
    cout<<"4：排序"<<endl;
    cout<<"0：退出"<<endl;
    cout<<"请输入选择：";
}

admin::~admin()
{
}

//注册
void admin::regist()
{
    vector<stu> a;
    readFromFile(stupath,&a);
    int x;
    string y;
    cout<<"请输入学生ID:";
    cin>>x;
    for(auto i:a)
    {
        if(i.getI() == x)
        {
            cout<<"ID重复!"<<endl;
            sleep(1);
            a.clear();
            return;
        }
    }
    cout<<"请输入其姓名：";
    cin>>y;
    a.push_back(stu(x,y));
    writeToFile(stupath,&a);
    a.clear();
}

//注销
void admin::cancel()
{
    vector<stu> a;
    readFromFile(stupath,&a);
    int x;
    cout<<"请输入学生ID:";
    cin>>x;
    for(vector<stu>::iterator it = a.begin();it!=a.end();it++)
    {
        if(it->getI() == x)
        {
            a.erase(it);
            writeToFile(stupath,&a);
            cout<<"注销成功!"<<endl;
            sleep(1);
            a.clear();
            return;
        }
    }
    cout<<"没有找到该学生!"<<endl;
    sleep(1);
    a.clear();
    return;
}
//查询
void admin::search()
{
    vector<stu> a;
    readFromFile(stupath,&a);
    int x;
    cout<<"请输入学生ID:";
    cin>>x;
    for(auto i:a)
    {
        if(i.getI() == x)
        {
            cout<<"ID:"<<i.getI()<<endl;
            cout<<"name:"<<i.getN()<<endl;
            cout<<"请输入任意键后回车继续-----";
            string deng;
            cin>>deng;
            a.clear();
            return;
        }
    }
    cout<<"没有找到该学生!"<<endl;
    sleep(1);
    a.clear();
    return;

}

//排序比较
bool stuCmp(stu&a,stu&b)
{
    return a.getI()<b.getI();
}

//排序
void admin::stuSort()
{
    vector<stu> a;
    readFromFile(stupath,&a);
    sort(a.begin(),a.end(),stuCmp);
    writeToFile(stupath,&a);
    cout<<"排序完成"<<endl;
    sleep(1);
    a.clear();
    return;
}

//读取
void readFromFile(string path,vector<stu> *a)
{
    ifstream in;
    in.open(path,fstream::in);
    if(!in.is_open())
    {
        cerr<<"error"<<endl;
        return;
    }
    stu tmp(0,"\0");
    while(in>>tmp)
    {
        a->push_back(tmp);
    }
    in.close();
}

//写入
void writeToFile(string path,vector<stu> *a)
{
    ofstream out;
    out.open(path,fstream::out);
    if(!out.is_open())
    {
        cerr<<"error"<<endl;
        return;
    }
    for(vector<stu>::iterator it = a->begin();it!=a->end();it++)
    {
        out<<*it<<endl;
    }
    out.close();
}